package com.sgb.kjwl.view.ui.adapter.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import androidx.core.util.Pair;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ItemOfferOwnerGeneralGoodsBinding;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.DateUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.List;

public class OfferOwnerGeneralAdapter extends BaseRecycleAdapter<OrderQuoteEntity> {

    private onEditClickListener onEditClickListener;

    public OfferOwnerGeneralAdapter(Context context, List<OrderQuoteEntity> data) {
        super(context, R.layout.item_offer_owner_general_goods, data);
    }

    public void setonEditClick(onEditClickListener editClickListener) {
        this.onEditClickListener = editClickListener;
    }

    public interface onEditClickListener {
        void onAgreeClick(OrderQuoteEntity entity);
    }

    @Override
    public void convert(ItemViewHolder holder, OrderQuoteEntity entity) {
        //设置绑定数据
        ItemOfferOwnerGeneralGoodsBinding binding = (ItemOfferOwnerGeneralGoodsBinding) holder.getmBinding();
        ImageView status_iv = holder.getView(R.id.status_iv);
        holder.itemView.findViewById(R.id.handle_btn).setVisibility(View.GONE);
        holder.itemView.findViewById(R.id.handle_bar).setVisibility(View.GONE);
        holder.itemView.findViewById(R.id.view_order).setVisibility(View.GONE);

        //报价状态：2.0.8  报价状态：offerStatus     1已报价  2已同意  5货主未同意
        switch (entity.getOfferStatus()) {
            case "1"://已报价
                binding.statusIv.setImageResource(R.mipmap.icon_offer_tobe_confirmed);
                binding.handleBar.setVisibility(View.VISIBLE);
                binding.handleBtn.setVisibility(View.VISIBLE);
                binding.viewOrder.setVisibility(View.GONE);
                binding.llReasonEffective.setVisibility(View.GONE);
                break;

            case "2"://待支付
                binding.statusIv.setImageResource(R.mipmap.offer_to_pay);
                binding.handleBar.setVisibility(View.GONE);
                binding.handleBtn.setVisibility(View.GONE);
                binding.viewOrder.setVisibility(View.GONE);
                binding.llReasonEffective.setVisibility(View.GONE);
                break;
            case "3"://已支付
                binding.statusIv.setImageResource(R.mipmap.offer_payed);
                binding.handleBar.setVisibility(View.VISIBLE);
                binding.handleBtn.setVisibility(View.GONE);
                binding.viewOrder.setVisibility(View.VISIBLE);
                binding.llReasonEffective.setVisibility(View.GONE);
                break;
            case "4"://超时未支付
                binding.statusIv.setImageResource(R.mipmap.offer_off_time);
                binding.handleBar.setVisibility(View.GONE);
                binding.handleBtn.setVisibility(View.GONE);
                binding.viewOrder.setVisibility(View.GONE);
                binding.llReasonEffective.setVisibility(View.GONE);
                break;
            case "5"://已失效
                binding.statusIv.setImageResource(R.mipmap.offer_off_time);
                binding.handleBar.setVisibility(View.GONE);
                binding.handleBtn.setVisibility(View.GONE);
                binding.viewOrder.setVisibility(View.GONE);
                binding.llReasonEffective.setVisibility(View.VISIBLE);
                String failureCause = "";
                if (entity.getFailureCause() != null) {
                    switch (entity.getFailureCause()) {
                        case 0:
                            failureCause = "车主超时未支付信息费";
                            break;
                        case 1:
                            failureCause = "货主未同意报价";
                            break;
                        case 2:
                            failureCause = "货主已下架货源";
                            break;
                        case 3:
                            failureCause = "货主已删除货源";
                            break;
                    }
                }
                binding.reasonEffective.setText(failureCause);
                break;
        }

        binding.tvName.setText(TextUtils.isEmpty(entity.getName()) ? "" : entity.getName());
        binding.tvPhone.setText(TextUtils.isEmpty(entity.getTelphone()) ? "" : entity.getTelphone());

        if (!TextUtils.isEmpty(entity.getQuotedPriceObject())) {
            switch (entity.getQuotedPriceObject()) {
                case "1"://企业
                case "2"://团队
                    binding.name.setText(TextUtils.isEmpty(entity.getCompanyName()) ? "" : entity.getCompanyName() + "");
                    binding.carInfoLayout.setVisibility(View.GONE);
                    break;
                case "3"://个人
                    binding.name.setText(TextUtils.isEmpty(entity.getCarNumber()) ? "" : entity.getCarNumber());
                    String carInfo = "";
                    if (!TextUtils.isEmpty(entity.getCarTypeName()))
                        carInfo += entity.getCarTypeName() + " ";
                    if (!TextUtils.isEmpty(entity.getCarLenName()))
                        carInfo += "车长" + entity.getCarLenName();
                    binding.carInfo.setText(TextUtils.isEmpty(carInfo) ? "/" : carInfo);
                    binding.carInfoLayout.setVisibility(View.VISIBLE);
                    break;
            }
        }

        if (!TextUtils.isEmpty(entity.getAllFreight())) {
            binding.freightAll.setText(NumberUtil.trim0(entity.getAllFreight()) + "元");
            if (!TextUtils.isEmpty(entity.getSourceAllFreight()) && !TextUtils.isEmpty(entity.getAllFreight())) {
                binding.freightAll.setTextColor(Double.parseDouble(entity.getAllFreight()) > Double.parseDouble(entity.getSourceAllFreight())
                        ? context.getResources().getColor(R.color.color_FF4B10) : context.getResources().getColor(R.color.color_secondary_yellow));
            }
        } else {
            binding.freightAll.setText("/");
        }

        if (!TextUtils.isEmpty(entity.getFreight())) {
            binding.freightOffer.setText(NumberUtil.trim0(entity.getFreight()) + entity.getQuotationFreightUnit());
        } else {
            binding.freightOffer.setText("/");
        }

        if (!TextUtils.isEmpty(entity.getCreateTime())) {
            binding.offerTime.setText(DateUtils.formatDate(String.valueOf(entity.getCreateTime()), ""));
        } else {
            binding.offerTime.setText("/");
        }

        binding.handleBtn.setOnClickListener(v -> checkCarInfo(entity));
        binding.viewOrder.setOnClickListener(v -> skipOrder(entity));

    }

    /**
     * 跳转货运订单详情
     *
     * @param entity
     */
    private void skipOrder(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOrderNo())) {
            //跳转竞价订单详情
            ActivityJump.jumpToActivity(context, TransportOrderDetailOwnerActivity.class, Pair.create("no", entity.getOrderNo()),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
        }
    }

    /**
     * 拨号检查
     *
     * @param entity
     */
    private void checkCanCall(OrderQuoteEntity entity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(context);
            return;
        }
        if (!TextUtils.isEmpty(entity.getTelphone())) {
            showCallDialog(entity.getTelphone());
        } else {
            ToastUtil.show(context, "无联系方式");
        }
    }

    /**
     * 交流检查
     *
     * @param entity
     */
    private void checkIm(OrderQuoteEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getImAccount())) {
//            NimUIKit.startP2PSession(context, entity.getImAccount());
            IMUtils.getInstance().buildSingleTalking(entity.getImAccount());
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

    /**
     * 检查车辆信息是否正常
     *
     * @param entity
     */
    private void checkCarInfo(OrderQuoteEntity entity) {
        showOfferDialog(entity);
    }

    /**
     * 展示同意报价对话框
     */
    private void showOfferDialog(OrderQuoteEntity entity) {
        String name = "";
        switch (entity.getQuotedPriceObject()) {
            case "1"://企业
            case "2"://团队
                name = entity.getCompanyName();
                break;
            case "3"://个人
                name = entity.getName();
                break;
        }
        String content = "";
        if (!TextUtils.isEmpty(entity.getMessagePrice())) {
            if (NumberUtil.convertToDouble(entity.getMessagePrice()) != 0) {
                content = "下单后，承运人支付信息费后生成货运订单，您确定要下单吗？";
            } else {
                content = "下单后，将生成货运订单，您确定要下单吗？";
            }
        }
        new RoundDialog.Builder(context)
                .title("提示")
                .content(content)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    if (onEditClickListener != null) {
                        onEditClickListener.onAgreeClick(entity);
                    }
                })
                .show();
    }

    /**
     * 拨打电话对话框
     *
     * @param number
     */
    private void showCallDialog(String number) {
        new RoundDialog.Builder(context)
                .title("确认呼叫")
                .content(number)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(number);
                    }
                })
                .show();
    }

    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }
}
